﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

namespace MLY.LTR.Contractors
{
  public partial class ContractoraddWoFrm : Bll.BasePage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!this.IsPostBack)
      {
        if (Request.ServerVariables["HTTP_REFERER"] == null)
          ViewState["Referer"] = this.Request.Url.ToString();
        else
          ViewState["Referer"] = Request.ServerVariables["HTTP_REFERER"];
      }
    }

    protected void workOrderFrm_ItemInserting(object sender, FormViewInsertEventArgs e)
    {
      try
      {
        System.Collections.Specialized.OrderedDictionary od = (System.Collections.Specialized.OrderedDictionary)e.Values;
        Dictionary<string, object> dic = new Dictionary<string, object>();
        foreach (string s in od.Keys)
          dic.Add(s, od[s]);
        dic.Add("CustomerId", int.Parse(((DropDownList)workOrderFrm.FindControl("ContractorIdDdl")).SelectedValue));
        dic.Add("ContractorId", SessParam.OrganizationId);
        Bll.clsWorkOrder.InsertWoFromDictionary(dic);

        showMsg(Dictionary.Translate("clientAddWo.successAddWo"), false, null);

        // Clear all Form View Control at the end of a successfull insert , in order to insert a new WO
        foreach (Control c in workOrderFrm.Controls)
        {
          ClearControls(c);
        }
        ((DropDownList)workOrderFrm.FindControl("ContractorIdDdl")).SelectedIndex = 0;

        e.SetValueToNull("PlannedDelivaryDate");
        e.SetValueToNull("ActualDelivaryDate");
      }
      catch (Exception ex)
      {
        showMsg(Dictionary.Translate("clientAddWo.UnableToAddWoFrm"), true, ex);
      }
      finally
      {
        e.Cancel = true;
      }
    }

    public void showMsg(string msg, bool isError, Exception myEx)
    {
      if (isError)
      {
        ErrMsg.Visible = true;
        SuccessMsg.Visible = false;
        ErrMsg.Text = msg;
        Bll.tblLogger.AddLogEntry(msg + ":" + myEx.Message, true);
      }
      else
      {
        ErrMsg.Visible = false;
        SuccessMsg.Visible = true;
        SuccessMsg.Text = msg;
        Bll.tblLogger.AddLogEntry(msg, false);

      }
    }

    public static void ClearControls(Control Parent)
    {
      if (Parent is TextBox)
      { (Parent as TextBox).Text = string.Empty; }
      else
      {
        foreach (Control c in Parent.Controls)
          ClearControls(c);
      }
    }

    protected void goBckBtn_Click(object sender, EventArgs e)
    {
      Response.RedirectTo((string)ViewState["Referer"]);
    }


  }
}
